const webpack = require('webpack');
const {injectBabelPlugin, getLoader} = require('react-app-rewired');
const rewireLess = require('react-app-rewire-less');
const loaderNameMatches = require("react-app-rewired").loaderNameMatches;
const {join, resolve} = require('path');
const {existsSync} = require('fs');
const rewireDecorators = require("react-app-rewire-decorators-legacy");
const rewireTypescript = require('react-app-rewire-typescript');

module.exports = function override (config, env) {
  // do stuff with the webpack config...
  console.log('-------------------env------------------');
  console.log(env);

  process.ENV = env;

  // 生产环境关闭sourcemap
  if (env === 'production') {
    config.devtool = false
  }

  config.plugins = config.plugins || [];
  config.resolve.plugins = []

  // 引入自定义可配置环境插件
  const settingsPlugin = require('./plugin/settings-plugin');
  config.plugins.push(settingsPlugin);

  // 按需加载antd
  config = injectBabelPlugin(['import', {libraryName: 'antd', libraryDirectory: 'es', style: true}], config);

  // 启用decorator
  config = rewireDecorators(config, env);

  // 启用TypeScript
  config = rewireTypescript(config, env);

  // 修改url-loader
  // 1.limit：10000 -> 1000
  const urlLoader = getLoader(config.module.rules, rule => loaderNameMatches(rule, 'url-loader'));
  urlLoader.options.limit = 1000;

  // 抽取公共js，vendor.js
  const vendorPlugin = new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks (module) {
      // any required modules inside node_modules are extracted to vendor
      return (
        module.resource &&
        /\.js$/.test(module.resource) &&
        module.resource.indexOf(
          join(__dirname, './node_modules')
        ) === 0
      )
    }
  });
  config.plugins.push(vendorPlugin);

  // 支持less，并且支持定制主题
  const pkgPath = join(__dirname, 'package.json');
  const pkg = existsSync(pkgPath) ? require(pkgPath) : {};

  let theme = {};
  if (pkg.theme && typeof(pkg.theme) === 'string') {
    let cfgPath = pkg.theme;
    // relative path
    if (cfgPath.charAt(0) === '.') {
      cfgPath = resolve(args.cwd, cfgPath);
    }
    const getThemeConfig = require(cfgPath);
    theme = getThemeConfig();
  } else if (pkg.theme && typeof(pkg.theme) === 'object') {
    theme = pkg.theme;
  }

  let options = {
    javascriptEnabled: true,
    "modifyVars": theme
  }
  config = rewireLess.withLoaderOptions(options)(config, env);

  if (env === 'development') {
    config.output.filename = 'static/js/[name].js'
  }

  // console.log('-------------------webpack config------------------');
  // console.log(config);
  return config;
};